<template>
  <div class="settings-page">
  <div class="container page">
    <div class="row">

      <div class="col-md-6 offset-md-3 col-xs-12">
        <h1 class="text-xs-center">Your Settings</h1>

        <form @submit.prevent="onSubmit">
          <fieldset>
            <fieldset class="form-group">
              <input v-model="userInfo.image" class="form-control" type="text" placeholder="URL of profile picture">
            </fieldset>
            <fieldset class="form-group">
              <input v-model="userInfo.username" class="form-control form-control-lg" type="text" placeholder="Your Name">
            </fieldset>
            <fieldset class="form-group">
              <textarea v-model="userInfo.bio" class="form-control form-control-lg" rows="8" placeholder="Short bio about you"></textarea>
            </fieldset>
            <fieldset class="form-group">
              <input v-model="userInfo.email" class="form-control form-control-lg" type="text" placeholder="Email">
            </fieldset>
            <fieldset class="form-group">
              <input v-model="userInfo.password" class="form-control form-control-lg" type="password" placeholder="Password">
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right">
              Update Settings
            </button>
          </fieldset>
        </form>
      </div>

    </div>
  </div>
</div>
</template>

<script>
import { mapState } from 'vuex'
import { update } from '@/api/user'

const Cookie = process.client ? require('js-cookie') : undefined

export default {
  name: 'SettingIndex',
  middleware: 'authenticated',
  computed: {
    ...mapState(['user'])
  },
  data() {
    return {
      userInfo: {
        image: '',
        username: '',
        bio: '',
        email: '',
        password: null
      },
      errors: {}
    }
  },
  methods: {
    async onSubmit () {
      try {
        const { data } = await update({
          user: this.userInfo
        })

        console.log(data)

        this.$store.commit('setUser', data.user)
        Cookie.set('user', data.user)
        this.$router.push(`/profile/${data.user.username}`)
      } catch (err) {
        this.errors = err.response.data.errors
      }
    }
  },
  mounted () {
    this.userInfo = {
      image: this.user.image,
      username: this.user.username,
      bio: this.user.bio,
      email: this.user.email,
      password: null
    }
  }
}
</script>

<style>

</style>